<?php defined('BASEPATH') OR die('No direct access allowed.');
/**
 * Description of Branches
 *
 * Created on Dec 20, 2010
 * @author Ramon Gutierrez
 * @copyright Bitstop Network Services Inc.
 * @version 0.1
 */
class Branches extends Controller {
	function Branches()	{
		parent::Controller();
		global $header, $data;
		
		// Check if user is logged in
		if(!$this->session->userdata('account_id') ||
		($this->session->userdata('account_type') != 'site_admin' && $this->session->userdata('account_type') != 'company')) {
			redirect(site_url(), 'refresh');
		}
		
		// Header variables
		$header['extras'] = "";
		$header['grid'] = false;
		$header['title'] = $this->lang->line('title_branches');
		$data['module'] = 'branches';
		
		// Include global models for this module
		$this->load->model('branches_model');
	}
	
	function index() {
		global $header, $data;
		
		// Load grid helper
		$this->load->helper('flexigrid');
		
		// Template variables
		$header['grid'] = true;
							
		// Load up that header!
		$this->load->view('header', $header);
		
		// Load the sidebar
		$this->load->view('sidebar-left', $data);
		
		// Flexigrid stuff
		if($this->session->userdata('account_type') == 'site_admin') {
			$colModel['b.activated'] = array('Active', 50, TRUE, 'center', 0);
			$colModel['c.name'] = array('Company', 155, TRUE, 'left', 2);
			$colModel['b.name'] = array('Name', 155, TRUE, 'left', 1);
			$colModel['branch_manager'] = array('Manager', 200, TRUE, 'left', 1);
			$colModel['b.product_key'] = array('Branch Validation Key', 200, TRUE, 'left', 1);
			$colModel['actions'] = array('Actions', 100, FALSE, 'left', 0);
		} else {
			$colModel['b.activated'] = array('Active', 50, TRUE, 'center', 0);
			$colModel['b.name'] = array('Name', 155, TRUE, 'left', 2);
			$colModel['branch_manager'] = array('Manager', 200, TRUE, 'left', 1);
			$colModel['b.product_key'] = array('Branch Validation Key', 200, TRUE, 'left', 1);
			$colModel['actions'] = array('Actions', 100, FALSE, 'left', 0);
		}
		
		// Confirm Flexigrid parameters
		$gridParams = array(
							'width' => 'auto',
							'height' => 'auto',
							'rp' => 50,
							'rpOptions' => '[10,15,20,25,50]',
							'pagestat' => 'Displaying: {from} to {to} of {total} items.',
							'blockOpacity' => 0.5,
							'title' => "<' + 'img src=\"" . site_url('images/branches.png') . "\" alt=\"\" /> Branches",
							'showTableToggleBtn' => false
						   );
		
		// Create Flexigrid buttons
		$buttons[] = array('New Branch', 'new', 'the_grid');
		$buttons[] = array('separator');
		$buttons[] = array('Select All', 'select', 'the_grid');
		$buttons[] = array('De-select All', 'deselect', 'the_grid');
		$buttons[] = array('separator');
		$buttons[] = array('Batch Edit', 'edit', 'the_grid');

		// Build the grid!
		$grid_js = build_grid_js('the_grid', site_url("ajax/branches_getrows/" . ($this->session->userdata('account_type') == 'company' ? $this->session->userdata('client_id') : "")), $colModel, 'b.name', 'asc', $gridParams, $buttons);
		$data['the_grid'] = $grid_js;
		
		// Dish out the meat
		$this->load->view('grid-index', $data);
		
		// Let's see that footer!
		$this->load->view('footer');
	}
	
	function edit($items) {
		global $header, $data;
		
		// Build the ID array
		$item_array = array_unique(explode(":", $items));
		
		// Template variables
		$header['extras'] = '<script type="text/javascript">' . "\n" .
							'// <![CDATA[' . "\n" .
							'  $(document).ready(function() {' . "\n" .
							'    var options = {' . "\n" .
							'        target:         "#response",' . "\n" .
							'        success:        showResponse' . "\n" .
							'    };' . "\n\n" .
							'    $("#theform").ajaxForm(options);' . "\n" .
							'    function showResponse(responseText, statusText) {' . "\n" .
							'      $("#response").html(responseText).show();' . "\n" .
							'      if(responseText == "Update successful") {' . "\n" .
							'        $("#response").css("border", "1px solid #c8fb6e");' . "\n" .
							'        $("#response").css("backgroundColor", "#eaffb9");' . "\n" .
							'        window.scrollTo(0,0);' . "\n" .
							'        alert(responseText);' . "\n" .
							'        window.location = "' . site_url($data['module']) . '/";' . "\n" .
							'        //alert(responseText);' . "\n" .
							'      } else {' . "\n" .
							'        $("#response").css("border", "1px solid #fa4646");' . "\n" .
							'        $("#response").css("backgroundColor", "#fabfbf");' . "\n" .
							'        submitted = false;' . "\n" .
							'        window.scrollTo(0,0);' . "\n" .
							'      }' . "\n" .
							'    };' . "\n" .
							'  });' . "\n" .
							'// ]]>' . "\n" .
							'</script>' . "\n\n";
		
		// Load up that header!
		$this->load->view('header', $header);
		
		// Load the sidebar
		$this->load->view('sidebar-left', $data);
		
		// Load the first part of the edit section
		$data['subtitle'] = $this->lang->line('subtitle_edit_branches');
		$this->load->view('edit-top', $data);
		
		// Initialize the idstring var
		$idstring = '';
		
		// Additional data
		$countries = $this->common_model->getCountries();
		
		// Counter var
		$i = 1;

		// Generate editable blocks for each item
		foreach($item_array as $item) {
			// Gather item info
			$row = $this->common_model->getInfo($data['module'], $item);
			
			if($row) {
				// Assign additional data to be passed
				$row['i'] = $i;
				$row['countries'] = $countries;
				
				// Get company name if admin
				if($this->session->userdata('account_type') == 'site_admin') {
					$row['company'] = $this->branches_model->getCompany($row['id']);
				}
				
				// Load the block
				$this->load->view('edit-row-branches', $row);
					
				// Add to idstring
				$idstring .= ($idstring ? "," . $row['id'] : $row['id']);
				
				// Increment counter
				$i++;
			}
		}
		
		// If no IDs exist, redirect to list
		if(!$idstring) {
			redirect(site_url($data['module']), 'refresh');
		}
		
		// Load the second part of the edit section
		$this->load->view('edit-bottom', array('idstring' => base64_encode($idstring)));
		
		// Let's see that footer!
		$this->load->view('footer');
	}
	
	function edit_ajax() {
		global $data;
		
		// Set module
		$module = $data['module'];
		
		// Generate ID array
		$ids = explode(",", base64_decode($this->input->post("idstring")));
		$error = false;

		foreach($ids as $id) {
			$i = $this->input->post("i" . $id);
			if(is_numeric($id)) {
				if($this->common_model->exists($module, $id)) {
					$info = $this->common_model->getInfo($module, $id);
					$post = array();

					$post['name'] = $this->input->post("name" . $id);
					$post['street_address'] = $this->input->post("street_address" . $id);
					$post['city'] = $this->input->post("city" . $id);
					$post['state'] = $this->input->post("state" . $id);
					$post['country_id'] = $this->input->post("country_id" . $id);
					$post['zip'] = $this->input->post("zip" . $id);
					$post['contact_number'] = $this->input->post("contact_number" . $id);
					
					// Check for duplicates
					$dupe_branchname = $this->db->select('id')->from('branches')->where("id != $id AND name = '" . $post['name'] . "' AND client_id = " . $info['client_id'])->get();

					$error .= !$post['name'] ? "<li>Enter a name for Branch $i.</li>" : ($dupe_branchname->num_rows() > 0 ? "<li>Name is already in use for Branch $i.</li>" : '');
					$error .= !$post['street_address'] ? "<li>Enter a street address for Branch $i.</li>" : '';
					$error .= !$post['city'] ? "<li>Enter a city for Branch $i.</li>" : '';
					$error .= !$post['state'] ? "<li>Enter a state or province for Branch $i.</li>" : '';
					$error .= !$post['country_id'] ? "<li>Select a country for Branch $i.</li>" : '';
					$error .= !$post['contact_number'] ? "<li>Provide a contact number for Branch $i.</li>" : '';
					
					if(!$error) {
						$data = array(
									  'name' => $post['name'],
									  'street_address' => $post['street_address'],
									  'city' => $post['city'],
									  'state' => $post['state'],
									  'country_id' => $post['country_id'],
									  'zip' => $post['zip'],
									  'contact_number' => $post['contact_number'],
									  'changed' => 1
									 );
						
						$query = $this->common_model->update($module, $id, $data);
						
						if($query) {
							// Log query goes here
						} else {
							$error .= "<li>Whoops! Something seems to have gone wrong. Please try again later.</li>";
						}
					}
				}
			}
		}
		
		if($error) {
			echo "<b>Please correct the following errors:</b><br /><ul class='errors'>$error</ul>";
		} else {
			echo "Update successful";
		}
	}
	
	function create() {
		global $header, $data;
		
		// Template variables
		$header['extras'] = '<link href="' . site_url('css/jquery.autocomplete.css') . '" rel="stylesheet" type="text/css" />' . "\n" .
							'<script type="text/javascript" src="' . site_url('js/jquery.autocomplete.js') . '"></script>' . "\n" .
							'<script type="text/javascript">' . "\n" .
							'// <![CDATA[' . "\n" .
							'  $(document).ready(function() {' . "\n" .
							'    var options = {' . "\n" .
							'        target:         "#response",' . "\n" .
							'        success:        showResponse' . "\n" .
							'    };' . "\n\n" .
							'    $("#theform").ajaxForm(options);' . "\n" .
							'    function showResponse(responseText, statusText) {' . "\n" .
							'      $("#response").html(responseText).show();' . "\n" .
							'      if(responseText == "Branch has been created") {' . "\n" .
							'        $("#response").css("border", "1px solid #c8fb6e");' . "\n" .
							'        $("#response").css("backgroundColor", "#eaffb9");' . "\n" .
							'        window.scrollTo(0,0);' . "\n" .
							'        alert(responseText);' . "\n" .
							'        window.location = "' . site_url($data['module']) . '/";' . "\n" .
							'        //alert(responseText);' . "\n" .
							'      } else {' . "\n" .
							'        $("#response").css("border", "1px solid #fa4646");' . "\n" .
							'        $("#response").css("backgroundColor", "#fabfbf");' . "\n" .
							'        submitted = false;' . "\n" .
							'        window.scrollTo(0,0);' . "\n" .
							'      }' . "\n" .
							'    };' . "\n" .
							'  });' . "\n" .
							'// ]]>' . "\n" .
							'</script>' . "\n\n";
		
		// Load up that header!
		$this->load->view('header', $header);
		
		// Load the sidebar
		$this->load->view('sidebar-left', $data);
		
		// Additional data
		$data['countries'] = $this->common_model->getCountries();
		
		// Dish out the meat
		$this->load->view('create-branches', $data);
		
		// Let's see that footer!
		$this->load->view('footer');
	}
	
	function create_ajax() {
		// Branch info
		$post['name'] = $this->input->post("name");
		$post['street_address'] = $this->input->post("street_address");
		$post['city'] = $this->input->post("city");
		$post['state'] = $this->input->post("state");
		$post['country_id'] = $this->input->post("country_id");
		$post['zip'] = $this->input->post("zip");
		$post['contact_number'] = $this->input->post("contact_number");
		$post['company'] = $this->session->userdata('account_type') == 'site_admin' ? $this->input->post("company") : false;
		
		// Branch Manager info
		$post['first_name'] = $this->input->post("a_first_name");
		$post['last_name'] = $this->input->post("a_last_name");
		$post['a_street_address'] = $this->input->post("a_street_address");
		$post['a_city'] = $this->input->post("a_city");
		$post['a_state'] = $this->input->post("a_state");
		$post['a_country_id'] = $this->input->post("a_country_id");
		$post['a_zip'] = $this->input->post("a_zip");
		$post['a_contact_number'] = $this->input->post("a_contact_number");
		$post['email'] = $this->input->post("a_email");
		$post['username'] = $this->input->post("acct_username");
		$post['password'] = $this->input->post("acct_password");
		$post['confirm'] = $this->input->post("acct_confirm");
		$error = false;
		
		// Get client ID
		if($this->session->userdata('account_type') == 'site_admin' && $post['company']) {
			$client_str = explode("[ID: ", str_replace("]", "", $post['company']));
			$client_id = $client_str[1];
		} else {
			$client_id = $this->session->userdata('client_id');
		}
		
		// Check for duplicates
		$dupe_branchname = $this->db->select('id')->from('branches')->where("name = '" . $post['name'] . "' AND client_id = " . $client_id)->get();
		$dupe_username = $this->db->select('id')->from('accounts')->where("username", $post['username'])->get();
		$dupe_email = $this->db->select('id')->from('accounts')->where("email", $post['email'])->get();
		
		// Check for errors
		$error .= !$post['name'] ? "<li>Enter a name for this branch.</li>" : ($dupe_branchname->num_rows() > 0 ? "<li>Branch name is already in use.</li>" : '');
		$error .= !$post['street_address'] ? "<li>Enter a street address.</li>" : '';
		$error .= !$post['city'] ? "<li>Enter a city name.</li>" : '';
		$error .= !$post['state'] ? "<li>Enter a state or province.</li>" : '';
		$error .= !$post['country_id'] ? "<li>Select a country for this branch.</li>" : '';
		$error .= !$post['contact_number'] ? "<li>Provide a contact number for this branch.</li>" : '';
		$error .= !$post['company'] && $this->session->userdata('account_type') == 'site_admin' ? "<li>No company specified.</li>" : '';
		$error .= !$post['first_name'] || !$post['last_name'] ? "<li>Provide the branch manager's full name.</li>" : '';
		$error .= !$post['a_contact_number'] ? "<li>Missing contact number for branch manager.</li>" : '';
		$error .= !$post['email'] || !validate_email($post['email']) ? "<li>Provide a valid e-mail address.</li>" : ($dupe_email->num_rows() > 0 ? "<li>E-mail address is already in use.</li>" : '');
		$error .= !$post['username'] || strlen($post['username']) < 5 ? "<li>Username must have at least 5 characters.</li>" : ($dupe_username->num_rows() > 0 ? "<li>Username is already taken.</li>" : '');
		$error .= !$post['password'] || strlen($post['password']) < 7 ? "<li>Password must have at least 7 characters.</li>" : '';
		$error .= $post['confirm'] != $post['password'] ? "<li>Password and confirmation fields must match.</li>" : '';
		
		if(!$error) {
			$data = array(
						  'last_name' => $post['last_name'],
						  'first_name' => $post['first_name'],
						  'street_address' => $post['a_street_address'],
						  'city' => $post['a_city'],
						  'state' => $post['a_state'],
						  'country_id' => $post['a_country_id'],
						  'zip' => $post['a_zip'],
						  'email' => $post['email'],
						  'contact_number' => $post['a_contact_number'],
						  'username' => $post['username'],
						  'password' => md5($post['password']),
						  'account_type' => 'manager'
						 );
						 
			$query1 = $this->common_model->create('accounts', $data);
			$query2 = false;
			
			if($query1) {
				// Generate unique product key
				$product_key = $this->common_model->create_key();
				
				$data = array(
							  'name' => $post['name'],
							  'street_address' => $post['street_address'],
							  'city' => $post['city'],
							  'state' => $post['state'],
							  'country_id' => $post['country_id'],
							  'zip' => $post['zip'],
							  'contact_number' => $post['contact_number'],
							  'account_id' => $query1,
							  'client_id' => $client_id,
							  'product_key' => $product_key
							 );
				
				$query2 = $this->common_model->create('branches', $data);
			}
			
			if(!$query1 || !$query2) {
				$error .= "<li>Whoops! Something seems to have gone wrong. Please try again later.</li>";
			}
		}
		
		if($error) {
			echo "<b>Please correct the following errors:</b><br /><ul class='errors'>$error</ul>";
		} else {
			// Send confirmation e-mail
			$this->email->from('noreply@queue-systems.com', $this->lang->line('app_title'));
			$this->email->to($post['email']);
			$this->email->subject($this->lang->line('signup_email_subject'));
			$this->email->message($this->lang->line('signup_email_body_head') . "\r\n\r\n" .
								  $this->lang->line('signup_company_name') . ': ' . $this->session->userdata('company_name') . "\r\n" .
								  $this->lang->line('branch_name') . ': ' . $post['name'] . "\r\n\r\n" .
								  $this->lang->line('username') . ': ' . $post['username'] . "\r\n" .
								  $this->lang->line('password') . ': ' . $post['password'] . "\r\n\r\n" .
								  $this->lang->line('local_email_body_foot'));
			$this->email->send();
			
			// Success!
			echo "Branch has been created";
		}
	}
	
	function del() {
		// Retrieve post var
		$id = $this->input->post("ids");

		// Get item info
		$info = $this->common_model->getInfo('branches', $id, "name, account_id");
			
		if($info) {
			// Run the delete query
			$query1 = $this->common_model->delete('branches', $id);
			$query2 = $this->common_model->delete('accounts', $info['account_id']);
			
			// Return results
			if($query1 && $query2) {
				//$this->logs_model->add($this->session->userdata("user_id"), 1, 0, 0, $this->session->userdata('post_id'), 'Deleted Announcement (' . $info['title'] . ')');
				echo "Deletion was successful.";
			} else {
				echo "Error deleting the selected row. Please try again later.";
			}
		} else {
			echo "This item does not exist in the database.";
		}
	}
	
	function getCompanies($str = false) {
		// Get all company matches
		$rows = $this->common_model->getCompanies($str);
		
		if($rows) {
			foreach($rows->result() as $row) {
				echo "$row->name - " . $row->owner . " [ID: $row->id]\r\n";
			}
		}
	}
}